<!-- 评论组件： https://readpage.github.io/undraw-ui/components/comment.html#comment-%E4%BA%8B%E4%BB%B6 -->
<template>
  <div v-loading="loading" class="comment-section">
    <u-comment-scroll :disable="disable" @more="more">
      <u-comment
        :config="config"
        @submit="submit"
        @reply-page="replyGetPage"
        @before-data="beforeData"
      >
        <!-- <template>导航栏卡槽</template> -->
        <template #header>
          <div class="header-box flex justify-between items-center">
            <span class="text-lg font-bold">评论</span>
            <div class="flex items-center">
              <!-- <el-icon :size="18">
            <Heart />
          </el-icon>
          <span class="text-sm ml-2">100</span> -->
              <!-- <el-icon :size="18" class="ml-2">
                <Star />
              </el-icon>
              <span class="text-sm ml-2">20</span> -->
            </div>
          </div>
        </template>
        <template #operate="scope">
          <Operate :comment="scope" @remove="remove" @report="report" />
        </template>
        <!-- <template #action="{ user }">动作卡槽{{ user.username }}</template> -->
        <!-- <template #avatar="{ id, user }">头像卡槽{{ user.avatar }}</template> -->
        <!-- <template #info>信息卡槽</template> -->
        <!-- <template #card>用户信息卡片卡槽</template> -->
        <!-- <template #func>功能区域卡槽</template> -->
      </u-comment>
    </u-comment-scroll>
    <div v-if="isEmpty" class="empty-box flex justify-center items-center h-full">
      <el-empty description="这是一片荒地" />
    </div>
  </div>
</template>

<script setup>
import { reactive } from "vue";
import { usePage, cloneDeep } from "undraw-ui";
import Operate from "./operate.vue";
import { addComment, getCommentList, addReply, getCommentDetail } from "@/api/article";
import { useUserStore } from "@/store";
const emit = defineEmits(["report"]);
const props = defineProps({
  articleId: {
    type: String,
    default: "",
  },
});
const userInfo = useUserStore().userInfo;
const loading = ref(false);
const isEmpty = ref(false);
const config = reactive({
  user: {
    avatar: userInfo.avatar,
    nickname: userInfo.nickname,
    username: userInfo.username,
  },
  // 当前用户信息
  comments: [], // 评论数据
  relativeTime: true, // 开启人性化时间
  show: {
    level: false, // 关闭等级显示
    homeLink: false, // 关闭个人主页链接跳转
    address: false, // 关闭地址信息
    likes: false, // 关闭点赞按钮显示
  },
  page: true,
});
// 评论分页
const commentPage = ref({
  pageNum: 1,
  pageSize: 10,
  total: 0,
});
/**
 * 评论对象数据结构
 * 存储结构: 一个评论表，通过paretnId是否为空判断类型 评论/回复
 * 层数: 两层
 * 第一层：评论 parentId属性为空; 第二层关系: id等于parentId的数据，则为第二层回复的评论数据
 * 第二层: 回复 parentId属性不为空; 第一层关系: parentId等于第一层id，则为第一层评论的回复数据
 *
 */
const comments = [
  {
    id: "1",
    parentId: null,
    uid: "2",
    content:
      '床前明月光，疑是地上霜。<br>举头望明月，低头思故乡。<img class="a" id="a" style="width: 50px" src=a onerror="window.location.href=\'https://baidu.com\'">',
    //createTime: new Time().add(-1, 'day'),
    user: {
      username: "李白 [唐代]",
      avatar: "https://static.juzicon.com/images/image-231107185110-DFSX.png",
      homeLink: "/1",
    },
    reply: {
      total: 1,
      list: [
        {
          id: "11",
          parentId: 1,
          uid: "1",
          content: "🤪🤗😒",
          //createTime: new Time().add(-3, 'day'),
          user: {
            username: "杜甫 [唐代]",
            avatar: "https://static.juzicon.com/images/image-180327173755-IELJ.jpg",
          },
        },
      ],
    },
  },
  {
    id: "2",
    parentId: null,
    uid: "3",
    content:
      "国破山河在，城春草木深。<br>感时花溅泪，恨别鸟惊心。<br>烽火连三月，家书抵万金。<br>白头搔更短，浑欲不胜簪。",
    //createTime: new Time().add(-5, 'day'),
    user: {
      username: "杜甫 [唐代]",
      avatar: "https://static.juzicon.com/images/image-180327173755-IELJ.jpg",
    },
  },
  {
    id: "3",
    parentId: null,
    uid: "2",
    content: "日照香炉生紫烟，遥看瀑布挂前川。<br>飞流直下三千尺，疑是银河落九天。",
    likes: 34116,
    //createTime: new Time().add(-2, 'month'),
    user: {
      username: "李白 [唐代]",
      avatar: "https://static.juzicon.com/images/image-231107185110-DFSX.png",
      homeLink: "/1",
    },
  },
];
/**
 * 评论----------------------------------
 *
 */
// 提交评论事件
const submit = async ({ content, parentId, finish }) => {
  try {
    let params = {
      articleId: props.articleId,
      content: content,
      id: parentId,
    };
    if (parentId) {
      await addReply(params);
      ElMessage.success("回复成功");
    } else {
      await addComment(params);
      ElMessage.success("评论成功");
    }
    await getCommentListMethod();
    finish();
  } catch (error) {
    console.error(error);
  } finally {
  }
};
// 加载前评论数据处理 自定义别名nickname转换username
function beforeData(val) {
  val.user.username = val.user.nickname;
}
// 评论滚动条禁用
const disable = ref(false);
const getCommentListMethod = async () => {
  loading.value = true;
  try {
    const { list } = await getCommentList({
      articleId: props.articleId,
      pageNum: commentPage.value.pageNum,
      pageSize: commentPage.value.pageSize,
      replayPageSize: 5, // 回复分页大小, 插件固定是5条，超过5条才能调reply，没找到可以修改配置的地
    });
    let comments = list.map((item) => {
      return {
        ...item.comment,
        reply: {
          total: item.replayCount,
          list: item.replays,
        },
      };
    });
    // 动态加载评论数据
    config.comments = usePage(commentPage.value.pageNum, commentPage.value.pageSize, comments);
    let isMore = commentPage.pageNum <= Math.ceil(commentPage.total / commentPage.pageSize);
    !isMore && (disable.value = true);
    // 如果评论为空，则显示空状态
    if (config.comments.length === 0) {
      isEmpty.value = true;
      document.querySelector(".scroll-btn").style.display = "none";
    }
  } catch (error) {
    console.error(error);
  } finally {
    loading.value = false;
  }
};
// 加载更多评论
const more = () => {
  let isMore = commentPage.pageNum <= Math.ceil(commentPage.total / commentPage.pageSize);
  if (isMore) {
    commentPage.pageNum++;
    getCommentListMethod();
  }
};
/**
 * 回复----------------------------------
 *
 */
// 模拟请求接口分页 请求覆盖评论对应的回复数据(全量覆盖回复数据)
const replyGetPage = async ({ parentId, current, size, finish }) => {
  try {
    const { list, total } = await getCommentDetail({
      firstParentId: parentId,
      pageNum: current,
      pageSize: size,
    });
    finish({
      total,
      list,
    });
  } catch (error) {
    console.error(error);
  }
};
/**
 * 举报评论
 */
const report = (comment) => {
  emit("report", comment);
};
watch(
  () => props.articleId,
  () => {
    disable.value = false;
    getCommentListMethod();
    isEmpty.value = false;
  },
  {
    immediate: true,
  }
);
</script>

<style lang="scss" scoped>
.comment-section {
  height: 43vh;
  position: relative;
}

.u-comment {
  padding: 0 !important;
  border-top: 1px solid #f0f2f5;
}

:deep(.u-comment-scroll) {
  .scroll-btn {
    bottom: -1vh !important;

    > p {
      font-size: 12px;
    }
  }
}
</style>
